package cxp.xuexi.maven_shiro.configuration;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * Created by ASUS on 2018/2/20.
 */

public class WebContainerConfig implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context=new AnnotationConfigWebApplicationContext();
        context.setServletContext(servletContext);
        //把SpringMVC的配置注册进来
        context.register(SpringmvcConfig.class);
        context.register(MybatisConfig.class);
        ServletRegistration.Dynamic disPatcherServlet = servletContext.addServlet("DisPatcherServlet"
                ,new DispatcherServlet(context));
        disPatcherServlet.addMapping("/");
        disPatcherServlet.setLoadOnStartup(1);
        disPatcherServlet.setAsyncSupported(true);

        CharacterEncodingFilter characterEncodingFilter=new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration.Dynamic characterFilter = servletContext.addFilter("characterEncodingFilter",characterEncodingFilter);
        characterFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD,DispatcherType.INCLUDE),
                true,"/*");

        //配置Druid连接也管理页面
        ServletRegistration.Dynamic servlet = servletContext.addServlet("DruidStatView",new StatViewServlet());
        servlet.addMapping("/druid/*");
        servlet.setInitParameter("loginUsername","admin");
        servlet.setInitParameter("loginPassword","123456");

        WebStatFilter webStatFilter =new WebStatFilter();
        FilterRegistration.Dynamic filter= servletContext.addFilter("DruidWebStatFilter",webStatFilter);
        filter.setInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD,DispatcherType.INCLUDE),
                true,"/*");
    }
}
